﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Linq;
using Common.Library;
using Microsoft.Phone.BackgroundTransfer;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Tasks;
using MarkHeath.StarRating;
using System.Threading;
using System.Globalization;
using OnlineVideos.Views;
using OnlineVideos.Library;
using OnlineVideos.Common;
using OnlineVideos.UI;
using OnlineVideos.Data;
using OnlineVideos.Entities;
using System.ComponentModel;
using Common.Utilities;
using Microsoft.Phone.BackgroundAudio;
using System.Windows.Resources;
using System.IO;
using OnlineVideos.View_Models;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Phone.Shell;
using FlurryWP8SDK.Models;
using HtmlAgilityPack;
using System.Windows.Controls.Primitives;


namespace OnlineVideos
{
    public partial class DownloadList : PhoneApplicationPage
    {
        #region Global
        bool IsDataLoaded;
        Popup poupRename = default(Popup);
        List<ShowList> objtoprated = null;
        List<ShowList> objrecent = null;
        List<ShowList> objtamil = null;
        List<ShowList> objupcoming = null;
        List<ShowCategories> objcat = null;
        List<DownloadStatus> download = new List<DownloadStatus>();
        int topratedCount;
        int recentCount;
        int tamilCount;
        int upcomingCount;
        int rateindex;
        string index = string.Empty;
        string youtubeurl;
        private bool WebMediaFavStatus = false;
        private int DownloadCancelId = 0;
        private WebClient webClient1 = new WebClient();
        public static DownloadList current = null; 
        #endregion

        #region Constructor

        public DownloadList()
        {
            try
            {
                InitializeComponent();
                current = this;
                topratedCount = Constants.PageSize;
                recentCount = Constants.PageSize;
                tamilCount = Constants.PageSize;
                upcomingCount = Constants.PageSize;
                rateindex = 0;

                LoadPivotThemes();
                LoadDownLoadTheme();
                IsDataLoaded = false;
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in Shows Method In Shows file.", ex);
            }

        }

        #endregion

        #region PageLoad

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (ResourceHelper.AppName != Apps.Indian_Cinema_Pro.ToString() && ResourceHelper.AppName != Apps.Kids_TV_Pro.ToString() && ResourceHelper.AppName != Apps.Story_Time_Pro.ToString())
                LoadAds();
            try
            {
                FlurryWP8SDK.Api.LogEvent("DownloadList Page", true);
                if (ResourceHelper.ProjectName != "Web Tile" && ResourceHelper.ProjectName != "Video Mix" && ResourceHelper.AppName != Apps.Web_Media.ToString())
                {
                    ApplicationBarIconButton b = (ApplicationBarIconButton)ApplicationBar.Buttons[0];
                    b.Text = "Add" + " " + AppResources.Type;
                }
                else
                {
                    ApplicationBar.IsVisible = false;
                }
                if (IsDataLoaded == false)
                {
                    if (rateindex != 0)
                    {
                        pvtVideos.SelectedIndex = rateindex;
                        rateindex = 0;
                    }

                    PageHelper.RemoveEntryFromBackStack("Videos");

                    string name = string.Empty;
                    if (NavigationContext.QueryString.TryGetValue("name", out name))
                    {
                        tblkVideosTitle.Text = name.ToUpper();
                    }
                    if (ResourceHelper.AppName == Apps.Web_Media.ToString())
                        tblkVideosTitle.Text = "MEDIA FILES";
                    if (NavigationContext.QueryString.TryGetValue("index", out index))
                    {
                        if (index != "" && index != null)
                        {
                            pvtVideos.SelectedIndex = int.Parse(index);

                        }

                    }

                    try
                    {
                        GetPageDataInBackground();
                    }
                    catch (Exception ex)
                    {
                        Exceptions.SaveOrSendExceptions("Exception in PhoneApplicationPage_Loaded Method In Shows file.", ex);
                    }
                }
                performanceProgressBar.IsIndeterminate = false;

            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in PhoneApplicationPage_Loaded Method In Shows file.", ex);
            }
        }

        #endregion

        #region "Common Methods"
        private void LoadAds()
        {
            try
            {
                PageHelper.LoadAdControl(LayoutRoot, adstackpl, 2);
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in LoadAds Method In SongDetails file", ex);
                string excepmess = "Exception in LoadAds Method In SongDetails file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }

        }
        public void GetPageDataInBackground()
        {
            BackgroundHelper bwHelper = new BackgroundHelper();
            performanceProgressBar.IsIndeterminate = true;
            bwHelper.AddBackgroundTask(
                                        (object s, DoWorkEventArgs a) =>
                                        {
                                            a.Result = OnlineShow.GetTopRatedShows(topratedCount);
                                        },
                                        (object s, RunWorkerCompletedEventArgs a) =>
                                        {
                                            objtoprated = (List<ShowList>)a.Result;
                                            if (objtoprated.Count != 0)
                                            {
                                                lbxTopRated.ItemsSource = (List<ShowList>)a.Result;
                                                tblkToprated.Visibility = Visibility.Collapsed;

                                            }
                                            else
                                            {
                                                lbxTopRated.ItemsSource = null;
                                                tblkToprated.Visibility = Visibility.Visible;
                                                if (ResourceHelper.ProjectName == "Web Tile")
                                                    tblkToprated.Text = "no tiles available";
                                            }
                                            if (ResourceHelper.ProjectName == AppResources.VideoMix)
                                            {
                                                tblkToprated.Text = "No Video mixes Available";
                                            }
                                            if (ResourceHelper.AppName == Apps.Web_Media.ToString())
                                                tblkToprated.Text = "no downloads available";
                                            performanceProgressBar.IsIndeterminate = false;
                                        }
                                      );

            bwHelper.AddBackgroundTask(
                                        (object s, DoWorkEventArgs a) =>
                                        {
                                            a.Result = OnlineShow.GetRecentlyAddedShows(recentCount);
                                        },
                                        (object s, RunWorkerCompletedEventArgs a) =>
                                        {
                                            objrecent = (List<ShowList>)a.Result;
                                            if (objrecent.Count != 0)
                                            {
                                                lbxRecentlyAdded.ItemsSource = (List<ShowList>)a.Result;
                                                tblkrecent.Visibility = Visibility.Collapsed;
                                            }
                                            else
                                            {
                                                lbxRecentlyAdded.ItemsSource = null;
                                                tblkrecent.Visibility = Visibility.Visible;
                                                if (ResourceHelper.ProjectName == "Web Tile")
                                                    tblkrecent.Text = "no tiles available";
                                            }
                                            if (ResourceHelper.ProjectName == AppResources.VideoMix)
                                            {
                                                tblkrecent.Text = "No Video mixes Available";
                                            }
                                            if (ResourceHelper.AppName == Apps.Web_Media.ToString())
                                                tblkrecent.Text = "no downloads available";
                                            performanceProgressBar.IsIndeterminate = false;
                                        }
                                      );
            if (AppSettings.ProjectName == "Indian Cinema" || AppSettings.ProjectName == "Indian Cinema Pro")
            {
                bwHelper.AddBackgroundTask(
                                          (object s, DoWorkEventArgs a) =>
                                          {
                                              a.Result = OnlineShow.GetTamilAddedShows(tamilCount);
                                          },
                                          (object s, RunWorkerCompletedEventArgs a) =>
                                          {
                                              objtamil = (List<ShowList>)a.Result;
                                              if (objtamil.Count != 0)
                                              {
                                                  lbxTamilAdded.ItemsSource = (List<ShowList>)a.Result;
                                                  //tblkrecent.Visibility = Visibility.Collapsed;
                                              }
                                              else
                                              {
                                                  lbxTamilAdded.ItemsSource = null;
                                                  //tblkrecent.Visibility = Visibility.Visible;
                                              }
                                              //if (ResourceHelper.ProjectName == AppResources.VideoMix)
                                              //{
                                              //    tblkrecent.Text = "No Video mixes Available";
                                              //}
                                              performanceProgressBar.IsIndeterminate = false;
                                          }
                                        );
            }
            //if (AppSettings.ProjectName == "Indian Cinema" || AppSettings.ProjectName == "Indian Cinema Pro")
            //{
            //    bwHelper.AddBackgroundTask(
            //                              (object s, DoWorkEventArgs a) =>
            //                              {
            //                                  a.Result = OnlineShow.GetUpComingAddedShows(upcomingCount);
            //                              },
            //                              (object s, RunWorkerCompletedEventArgs a) =>
            //                              {
            //                                  objupcoming = (List<ShowList>)a.Result;
            //                                  if (objupcoming.Count != 0)
            //                                  {
            //                                      lbxUpcomingAdded.ItemsSource = (List<ShowList>)a.Result;
            //                                      //tblkrecent.Visibility = Visibility.Collapsed;
            //                                  }
            //                                  else
            //                                  {
            //                                      lbxUpcomingAdded.ItemsSource = null;
            //                                      //tblkrecent.Visibility = Visibility.Visible;
            //                                  }
            //                                  //if (ResourceHelper.ProjectName == AppResources.VideoMix)
            //                                  //{
            //                                  //    tblkrecent.Text = "No Video mixes Available";
            //                                  //}
            //                                  performanceProgressBar.IsIndeterminate = false;
            //                              }
            //                            );
            //}
            if (AppResources.ShowCategoryPivot)
            {
                bwHelper.AddBackgroundTask(
                                            (object s, DoWorkEventArgs a) =>
                                            {
                                                if (ResourceHelper.AppName == Apps.Web_Tile.ToString())
                                                {
                                                    a.Result = OnlineShow.LoadCategoryListForWebTile();
                                                }
                                                else if (ResourceHelper.AppName == Apps.Cricket_Videos.ToString())
                                                {
                                                    a.Result = OnlineShow.LoadCategoryListForCricketVideos();
                                                }
                                                else
                                                {
                                                    a.Result = OnlineShow.LoadCategoryList();
                                                }
                                            },
                                            (object s, RunWorkerCompletedEventArgs a) =>
                                            {
                                                if (ResourceHelper.AppName == Apps.Web_Tile.ToString())
                                                {
                                                    objcat = (List<ShowCategories>)a.Result;

                                                    if (objcat.Count != 0)
                                                    {
                                                        tblknocat.Visibility = Visibility.Collapsed;
                                                        lbxCategory.ItemsSource = (List<ShowCategories>)a.Result;
                                                    }
                                                    else
                                                    {
                                                        lbxCategory.ItemsSource = null;
                                                        tblknocat.Visibility = Visibility.Visible;
                                                    }
                                                    performanceProgressBar.IsIndeterminate = false;
                                                }
                                                else if (ResourceHelper.AppName == Apps.Cricket_Videos.ToString())
                                                {
                                                    lbxCategory.ItemsSource = (List<ShowCategories>)a.Result;
                                                    performanceProgressBar.IsIndeterminate = false;
                                                }
                                                else
                                                {
                                                    lbxCategory.ItemsSource = (List<CatageoryTable>)a.Result;
                                                    performanceProgressBar.IsIndeterminate = false;
                                                }
                                            }
                                          );
            }
            if (AppSettings.AddNewShowIconVisibility == true)
            {
                List<DownloadInfo> objVideoList = new List<DownloadInfo>();
                performanceProgressBar.IsIndeterminate = true;
                bwHelper.AddBackgroundTask(
                                           (object s, DoWorkEventArgs a) =>
                                           {
                                               objVideoList = DownloadManager.LoadDownloadUrls();
                                           },
                                           (object s, RunWorkerCompletedEventArgs a) =>
                                           {
                                               if (objVideoList.Count != 0)
                                               {
                                                   DownLoadList();
                                               }
                                               else
                                               {
                                                   Constants.SaveDownloadList.Clear();
                                                   tblkNoDownloads.Visibility = Visibility.Visible;
                                                   lbxdownloading.Visibility = Visibility.Collapsed;
                                               }
                                               performanceProgressBar.IsIndeterminate = false;
                                           }
                                         );

            }

            bwHelper.RunBackgroundWorkers();
        }

        private void LoadDownLoadTheme()
        {
            if (AppSettings.AddNewShowIconVisibility == true)
            {
                if (ResourceHelper.ProjectName == "Web Tile")
                {
                    pvtdownload.Visibility = Visibility.Collapsed;
                    pvtVideos.Items.Remove(pvtdownload);
                }
                else
                {
                    pvtdownload.Visibility = Visibility.Visible;
                    pvtdownload.Header = "downloads";
                }
            }
            else
            {
                pvtdownload.Visibility = Visibility.Collapsed;
                pvtVideos.Items.Remove(pvtdownload);
            }
        }

        private void LoadPivotThemes()
        {

            if (AppSettings.ProjectName == "Indian Cinema" || AppSettings.ProjectName == "Indian Cinema Pro")
            {
                pvttop.Header = "hindi";
                pvtrecent.Header = "telugu";
                pvttamil.Header = "tamil";
                pvttamil.Visibility = Visibility.Visible;
                //pvtupcoming.Header = "upcoming movies";
                //pvtupcoming.Visibility = Visibility.Visible;
            }
            else
            {
                pvttop.Header = "top rated";
                pvtrecent.Header = "recent";
                pvttamil.Visibility = Visibility.Collapsed;
                pvtVideos.Items.Remove(pvttamil);
                //pvtupcoming.Visibility = Visibility.Collapsed;
                //pvtVideos.Items.Remove(pvtupcoming);
            }
            if (AppResources.ShowCategoryPivot != true)
            {
                pvtcat.Visibility = Visibility.Collapsed;
                pvtVideos.Items.Remove(pvtcat);
            }
            else
            {
                pvtcat.Header = AppResources.ShowCategoryPivotTitle.Split(',')[1];
                pvtcat.Visibility = Visibility.Visible;
            }
        }

        public void DownLoadList()
        {
            try
            {

                List<DownloadInfo> objVideoList = new List<DownloadInfo>();
                download.Clear();
                download.AddRange(Constants.SaveDownloadList);
                if (Constants.DownloadStatus == false)
                    objVideoList = DownloadManager.LoadDownloadUrls();
                int countlist = objVideoList.Count();
                if (countlist > 0)
                {
                    List<DownloadInfo> info = new List<DownloadInfo>();
                    var xquery = (from q in objVideoList select q);

                    foreach (var itm in xquery)
                    {
                        var listitm = Constants.SaveDownloadList.Where(k => k.Id == itm.FolderID).FirstOrDefault();
                        if (listitm == null)
                        {
                            List<DownloadStatus> downloadstatuslist = new List<DownloadStatus>();
                            
                            string link = "";
                            link = itm.LinkUrl;
                            string name = "";
                            name = itm.LinkUrl.ToString().Substring(itm.LinkUrl.ToString().LastIndexOf('/') + 1);
                            if (itm.LinkUrl.StartsWith("http://www.youtube.com/watch?v=") || itm.LinkUrl.Contains("youtube.com") || itm.LinkUrl.Contains("googlevideo.com/videoplayback"))
                            {
                                link = itm.LinkUrl.Replace("http://www.youtube.com/watch?v=", "");
                                name = itm.title;
                                name = name.Replace(":", "").Replace("|", "").Replace(".flv", "").Replace(".", "").Replace("&", "").Replace("#", "").Replace(";", "").Replace("title=", "");
                            }
                            if (itm.LinkUrl.StartsWith("http://www.dailymotion.com") || itm.LinkUrl.Contains("vimeo.com") || itm.LinkUrl.Contains("veoh.com") || itm.LinkUrl.Contains("metacafe.com") || itm.LinkUrl.Contains("sevenload.net"))
                            {
                                if (itm.LinkUrl.EndsWith(".jpg") || itm.LinkUrl.EndsWith(".png") || itm.LinkUrl.EndsWith(".gif"))
                                {

                                }
                                else
                                {
                                    link = itm.LinkUrl.Replace("http://www.youtube.com/watch?v=", "");
                                    name = itm.title;
                                    if(itm.LinkUrl.StartsWith("http://fcache.veoh.com/"))
                                        name = name.Replace(":", "").Replace("|", "").Replace(".flv", "").Replace("&", "").Replace("#", "").Replace(";", "").Replace("title=", "");
                                            else
                                    name = name.Replace(":", "").Replace("|", "").Replace(".flv", "").Replace(".", "").Replace("&", "").Replace("#", "").Replace(";", "").Replace("title=", "");
                                }
                            }
                            var ln = link;
                            WebClient wb = new WebClient();
                            wb.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wcDownloadList_DownloadProgressChanged);
                            if (itm.LinkUrl.StartsWith("http://www.youtube.com/watch?v=") || itm.LinkUrl.Contains("googlevideo.com/videoplayback") || itm.LinkUrl.StartsWith("http://www.dailymotion.com") || itm.LinkUrl.Contains("vimeo.com") || itm.LinkUrl.Contains("veoh.com") || itm.LinkUrl.Contains("metacafe.com") || itm.LinkUrl.Contains("sevenload.net"))
                            {
                                if (itm.LinkUrl.EndsWith(".jpg") || itm.LinkUrl.EndsWith(".png") || itm.LinkUrl.EndsWith(".gif") || (itm.LinkUrl.StartsWith("http://fcache.veoh.com/") && itm.LinkUrl.Contains(".jpg")) || (itm.LinkUrl.StartsWith("http://fcache.veoh.com/") && itm.LinkUrl.Contains(".png")))
                                {
                                    wb.OpenReadCompleted += new OpenReadCompletedEventHandler(wcDownloadList_OpenReadCompleted);
                                }
                                else
                                {
                                    wb.OpenReadCompleted += new OpenReadCompletedEventHandler(wcYoutubeReadCompleted_OpenReadCompleted);
                                }

                            }
                            else
                            {
                                wb.OpenReadCompleted += new OpenReadCompletedEventHandler(wcDownloadList_OpenReadCompleted);
                            }

                            wb.OpenReadAsync(new Uri(link.ToString(), UriKind.Absolute), itm.FolderID.ToString());
                            downloadstatuslist = DownloadManagerHelper.LoadList(name, link, int.Parse(itm.FolderID.ToString()),itm.ThumbNail);
                            download.AddRange(downloadstatuslist);
                            Constants.SaveDownloadList.AddRange(downloadstatuslist);
                            Constants.DownloadStatus = true;
                        }

                    }
                }
                else if (Constants.SaveDownloadList.Count == 0)
                {
                    tblkNoDownloads.Visibility = Visibility.Visible;
                    lbxdownloading.Visibility = Visibility.Collapsed;

                }
                lbxdownloading.ItemsSource = null;
                lbxdownloading.ItemsSource = Constants.SaveDownloadList;
            }


            catch (Exception ex)
            {
                string excepmess = "Exception in AddList Method In showlist file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
                Exceptions.SaveExceptionInLocalStorage(excepmess);
            }
        }
        //void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        //{
        //    List<DownloadStatus> downloadstatuslist = new List<DownloadStatus>();
        //    DownloadInfo data = (DownloadInfo)e.UserState;
        //    string video = null;
        //    string VideoUrl = string.Empty;
        //    try
        //    {
        //        if (e.Result.ToString().Contains("mediaURL%22%3A%22"))
        //        {
        //            video = Regex.Split(e.Result.ToString(), "mediaURL%22%3A%22")[2];

        //            VideoUrl = Regex.Split(video, "%22%7D%5D%7D%7D")[0].Replace("%3A", ":").Replace("%5C%2F", "/").Replace("%25", "%");
        //        }
        //        else
        //        {
        //            string[] videourl = Regex.Split(e.Result.ToString(), "src");
        //            foreach (string item in videourl)
        //            {
        //                if (item.Contains("http://www.youtube.com/embed/") || item.Contains("https://www.youtube.com/embed") || item.Contains("//www.youtube-nocookie.com/embed/") || item.Contains("www.youtube.com/embed/"))
        //                {
        //                    string videoid = Regex.Split(item, @"""")[1].Replace("http://www.youtube.com/embed/", "").Replace("https://www.youtube.com/embed/", "").Replace("//www.youtube.com/embed/", "").Replace("www.youtube.com/embed/", "").Replace("//www.youtube-nocookie.com/embed/", "");
        //                    string orgyoutubeid = "http://www.youtube.com/v/" + videoid + "&amp;hl=en&amp;fs=1&amp;rel=0";
        //                    AppSettings.Youtubelink = orgyoutubeid;
        //                    VideoUrl = videoid;
        //                }
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Exceptions.SaveOrSendExceptions("Exception in GetDownloadVideoUrlFromMetacafeSite Method In DownloadManagerDailyMotion.cs file", ex);

        //    }
        //    if (VideoUrl.Contains(".14"))
        //    {
        //        VideoUrl = Regex.Split(video, "%22%7D%5D%7D%7D")[0].Replace("%3A", ":").Replace("%5C%2F", "/").Replace("%25", "%");
        //    }
        //    else
        //    {
        //        try
        //        {
        //            if (e.Result.ToString().Contains("mediaURL%22%3A%22"))
        //            {
        //                video = Regex.Split(e.Result.ToString(), "mediaURL%22%3A%22")[1];
        //                VideoUrl = Regex.Split(video, "%22%7D%5D%7D%7D")[0].Replace("%3A", ":").Replace("%5C%2F", "/").Replace("%25", "%");
        //            }
        //            else
        //            {
        //                string[] videourl = Regex.Split(e.Result.ToString(), "src");
        //                foreach (string item in videourl)
        //                {
        //                    if (item.Contains("http://www.youtube.com/embed/") || item.Contains("https://www.youtube.com/embed") || item.Contains("//www.youtube-nocookie.com/embed/") || item.Contains("www.youtube.com/embed/"))
        //                    {
        //                        string videoid = Regex.Split(item, @"""")[1].Replace("http://www.youtube.com/embed/", "").Replace("https://www.youtube.com/embed/", "").Replace("//www.youtube.com/embed/", "").Replace("www.youtube.com/embed/", "").Replace("//www.youtube-nocookie.com/embed/", "");
        //                        string orgyoutubeid = "http://www.youtube.com/v/" + videoid + "&amp;hl=en&amp;fs=1&amp;rel=0";
        //                        AppSettings.Youtubelink = orgyoutubeid;
        //                        VideoUrl = videoid;
        //                    }
        //                }
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            //ex.Data.Add("LinkUrl", LinkUrl);
        //            Exceptions.SaveOrSendExceptions("Exception in GetDownloadVideoUrlFromMetacafeSite Method In DownloadManagerDailyMotion.cs file", ex);

        //        }
        //    }
        //    if (VideoUrl.Contains("metacafe") && VideoUrl.Contains(".mp4"))
        //        VideoUrl = VideoUrl.Substring(0, VideoUrl.IndexOf(".mp4") + ".mp4".Length);
        //    AppSettings.YoutubeUri = VideoUrl;
        //    if (AppSettings.Youtubelink.Contains("youtube"))
        //    {

        //        var httpClient = new HttpClient();
        //        if (AppSettings.Youtubelink.Contains("youtube.com/v/"))
        //        {
        //            if (AppSettings.Youtubelink.Contains("http://www.youtube.com/v/") || AppSettings.Youtubelink.Contains("https://www.youtube.com/v") || AppSettings.Youtubelink.Contains("www.youtube.com/v/"))
        //            {
        //                string videoid = AppSettings.Youtubelink.Replace("http://www.youtube.com/v/", "").Replace("https://www.youtube.com/v/", "").Replace("//www.youtube.com/v/", "").Replace("www.youtube.com/v/", "").Replace("//www.youtube-nocookie.com/v/", "");
        //                string orgyoutubeid = "http://www.youtube.com/v/" + videoid + "&amp;hl=en&amp;fs=1&amp;rel=0";
        //                AppSettings.Youtubelink = "http://www.youtube.com/watch?v=" + videoid;
        //            }

        //        }
        //        var url = new Uri(AppSettings.Youtubelink);
        //        AppSettings.Youtubelink = string.Empty;
        //        string name = data.title.Replace(":", "").Replace("|", "").Replace(".flv", "").Replace(".", "").Replace("&", "").Replace("#", "").Replace(";", "").Replace("/", "").Replace("?", "").Replace("=", "");
        //        WebClient wbmeta = new WebClient();
        //        wbmeta.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12";
        //        wbmeta.OpenReadAsync(new Uri(url.ToString(), UriKind.RelativeOrAbsolute), data.FolderID.ToString());
        //        wbmeta.OpenReadCompleted += wbmeta_OpenReadCompleted;
        //        //downloadstatuslist = DownloadManagerHelper.LoadList(name, url.ToString(), int.Parse(data.FolderID.ToString()));
        //        //download.AddRange(downloadstatuslist);
        //        //Constants.SaveDownloadList.AddRange(downloadstatuslist);
        //        //Constants.DownloadStatus = true;
        //        //lbxdownloading.ItemsSource = null;
        //        //lbxdownloading.ItemsSource = Constants.SaveDownloadList;
        //    }
        //    else
        //    {
        //        string link = AppSettings.YoutubeUri;
        //        string name = data.title.Replace("&title=", "").Replace(":", "").Replace("|", "").Replace(".flv", "").Replace(".", "").Replace("&", "").Replace("#", "").Replace(";", "").Replace("/", "").Replace("?", "").Replace("=", "").Replace("'", "");
        //        downloadstatuslist = DownloadManagerHelper.LoadList(name, link, int.Parse(data.FolderID.ToString()));
        //        download.AddRange(downloadstatuslist);
        //        Constants.SaveDownloadList.AddRange(downloadstatuslist);
        //        Constants.DownloadStatus = true;
        //        lbxdownloading.ItemsSource = null;
        //        lbxdownloading.ItemsSource = Constants.SaveDownloadList;
        //        WebClient wb1 = new WebClient();
        //        wb1.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12";
        //        wb1.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wcDownloadList_DownloadProgressChanged);
        //        wb1.OpenReadAsync(new Uri(VideoUrl, UriKind.RelativeOrAbsolute), data.FolderID.ToString());
        //        wb1.OpenReadCompleted += wb1_OpenReadCompleted;

        //    }
        //}

        //void wbmeta_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        //{
        //    string folderid = e.UserState.ToString();
        //    string link = "";
        //    Stream stream = (Stream)e.Result;
        //    StreamReader s = new StreamReader(stream);
        //    string html = s.ReadToEnd();
        //    s.Close();
        //    s.Dispose();
        //    stream.Close();
        //    stream.Dispose();

        //    GetYotubeUrl(html);
        //    GetYouTubeVideoTitle(html);
        //    link = AppSettings.YoutubeUri + "&title=" + AppSettings.ShowLinkTitle;
        //    string name = "";
        //    name = AppSettings.ShowLinkTitle.Replace(":", "").Replace("|", "").Replace(".flv", "").Replace(".", "").Replace("&", "").Replace("#", "").Replace(";", "").Replace("/", "").Replace("?", "").Replace("=", "");
        //    AppSettings.ShowLinkTitle = name;
        //    List<DownloadStatus> downloadstatuslist = new List<DownloadStatus>();
        //    downloadstatuslist = DownloadManagerHelper.LoadList(name, link, int.Parse(folderid));
        //    download.AddRange(downloadstatuslist);
        //    Constants.SaveDownloadList.AddRange(downloadstatuslist);
        //    Constants.DownloadStatus = true;
        //    lbxdownloading.ItemsSource = null;
        //    lbxdownloading.ItemsSource = Constants.SaveDownloadList;
        //    WebClient wc = new WebClient();
        //    wc.DownloadProgressChanged += wcDownloadList_DownloadProgressChanged;
        //    wc.OpenReadAsync(new Uri(link, UriKind.RelativeOrAbsolute), int.Parse(folderid));
        //    wc.OpenReadCompleted += wc_OpenReadCompleted;

        //}
        void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {

            DownloadManagerHelper.YoutubeWriteStream(e, download);

        }
        //public void dailyDownloadwp8(string LinkUrl, string data)
        //{


        //    WebClient web = new WebClient();
        //    web.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12";
        //    web.DownloadStringAsync(new Uri(LinkUrl, UriKind.RelativeOrAbsolute), data);
        //    web.DownloadStringCompleted += web_DownloadStringCompleted;


        //}

        //void web_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        //{
        //    string video = null;
        //    string data = e.UserState.ToString();
        //    string linkurl = data.Split('$')[0];
        //    string folderid = data.Split('$')[1];
        //    try
        //    {
        //        switch (dailyQuality.ld)
        //        {
        //            case dailyQuality.ld:
        //                video = Regex.Split(e.Result.ToString(), "stream_h264_ld_url")[1];
        //                break;
        //            case dailyQuality.sd:
        //                video = Regex.Split(e.Result.ToString(), "VIDEO_URL%22%3A%22")[1];
        //                break;
        //            case dailyQuality.hd:
        //                video = Regex.Split(e.Result.ToString(), "VIDEO_URL%22%3A%22")[1];
        //                break;
        //            case dailyQuality.hd720:
        //                video = Regex.Split(e.Result.ToString(), "VIDEO_URL%22%3A%22")[1];
        //                break;
        //            default:
        //                break;
        //        }


        //    }
        //    catch (Exception ex)
        //    {
        //        video = Regex.Split(e.Result.ToString(), "VIDEO_URL%22%3A%22")[1];
        //        //video = Regex.Split(pgdata, "sdURL%22%3A%22")[1];
        //        // ex.Data.Add("LinkUrl", LinkUrl);
        //        Exceptions.SaveOrSendExceptions("Exception in dailyDownload Method In DownloadManagerDailyMotion.cs file", ex);

        //    }

        //    video = Regex.Split(video, ",")[0];

        //    NormalDaily(video, linkurl, folderid);
        //}
        //private void NormalDaily(string data, string linkurls, string id)
        //{
        //    string astring = data.Replace("%3A", ":");
        //    astring = astring.Replace("%5C%2F", "/");
        //    astring = astring.Replace("%3F", "?");
        //    astring = astring.Replace("%3D", "=");
        //    astring = astring.Replace("%253D", "=");
        //    astring = astring.Replace("%253F", "?");
        //    astring = astring.Replace("%253A", ":");
        //    astring = astring.Replace("%252F", "/");
        //    astring = astring.Replace(@"\/", "/");
        //    astring = astring.Substring(astring.IndexOf("http://") + 7);
        //    astring = "http://" + astring.Substring(0, astring.Length - 1);
        //    AppSettings.YoutubeUri = astring;


        //    string link = AppSettings.YoutubeUri + "&title=" + linkurls.Substring(linkurls.LastIndexOf("/") + 1);

        //    List<DownloadStatus> downloadstatuslist = new List<DownloadStatus>();
        //    string name = linkurls.Substring(linkurls.LastIndexOf('/') + 1);
        //    downloadstatuslist = DownloadManagerHelper.LoadList(name, AppSettings.YoutubeUri, int.Parse(id));
        //    download.AddRange(downloadstatuslist);
        //    Constants.SaveDownloadList.AddRange(downloadstatuslist);
        //    Constants.DownloadStatus = true;
        //    lbxdownloading.ItemsSource = null;
        //    lbxdownloading.ItemsSource = Constants.SaveDownloadList;
        //    WebClient wb = new WebClient();
        //    wb.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12";
        //    wb.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wcDownloadList_DownloadProgressChanged);
        //    wb.OpenReadAsync(new Uri(astring, UriKind.RelativeOrAbsolute), id);
        //    wb.OpenReadCompleted += new OpenReadCompletedEventHandler(wcDownloadList_OpenReadCompleted);

        //}
        void wb1_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {

            try
            {


                DownloadManagerHelper.ReadDownloadStream(e, download);

            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in wb1_OpenReadCompleted Method In showlist.cs file", ex);

            }
        }

        private void LoadAudioSongd(string title)
        {
            try
            {
                int Showid = Convert.ToInt32(AppSettings.ShowID);
                string linktype = LinkType.Audio.ToString();
                var ShowLinksByType = Task.Run(async () => await Constants.connection.Table<ShowLinks>().Where(i => i.ShowID == Showid && i.LinkType == linktype).ToListAsync()).Result;
                foreach (var linkinfo in ShowLinksByType)
                {
                    AppSettings.AudioTitle = linkinfo.Title;
                    if (linkinfo.Title == title)
                    {
                        AudioTrack audioTrack = new AudioTrack();
                        audioTrack.BeginEdit();
                        string url = ResourceHelper.ProjectName + "/Songs/" + linkinfo.LinkUrl;
                        audioTrack.Source = new Uri(url, UriKind.RelativeOrAbsolute);
                        audioTrack.Title = linkinfo.Title;
                        audioTrack.EndEdit();
                        BackgroundAudioPlayer.Instance.Track = audioTrack;
                        BackgroundAudioPlayer.Instance.Play();
                        BackgroundAudioPlayer.Instance.PlayStateChanged += new EventHandler(Instance_PlayStateChanged);
                        AppSettings.AudioShowID = AppSettings.ShowID;
                    }
                    else
                    {
                        BackgroundAudioPlayer.Instance.Pause();
                        AppSettings.SongPlayImage = string.Empty;
                    }
                }
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in LoadAudioSongd Method In Shows file.", ex);
            }
        }

        private void GetDownloadExtensions()
        {
            try
            {

                string ext = string.Empty;
                try
                {
                    ext = System.IO.Path.GetExtension((lbxRecentlyAdded.SelectedItem as ShowList).Title);
                }
                catch (Exception ex)
                {
                    ext = System.IO.Path.GetExtension((lbxTopRated.SelectedItem as ShowList).Title);
                }
                if (ext == ".3gp" || ext == ".3g2" || ext == ".mp4" || ext == ".m4v" || ext == ".wmv")
                {
                    History objHistory = new History();
                    objHistory.SaveSongHistory(AppSettings.ShowID, AppSettings.Title);
                    DownloadManagerHelper.Playvideo(int.Parse(AppSettings.ShowID));
                    //PageHelper.NavigateToPlayDownloadedVideos(AppResources.PlayDownloadedVideos, AppSettings.ShowID);
                }
                else if (ext == ".mp3" || ext == "=low" || ext == ".wav" || ext == ".aac" || ext == ".amr" || ext == ".wma")
                {
                    History objHistory = new History();
                    objHistory.SaveAudioHistory(AppSettings.ShowID, AppSettings.Title);
                    try
                    {
                        LoadAudioSongd((lbxRecentlyAdded.SelectedItem as ShowList).Title);
                    }
                    catch (Exception ex)
                    {
                        LoadAudioSongd((lbxTopRated.SelectedItem as ShowList).Title);
                    }
                }
                else if (ext == ".jpg" || ext == ".png")
                {

                    PageHelper.NavigateToDownloadedImagePage(AppResources.DownloadImagePageName);
                    History objHistory = new History();
                    objHistory.SaveImageHistory(AppSettings.ShowID, AppSettings.Title);
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in GetDownloadExtensions Method In Videos file", ex);
            }
        }

        #endregion

        #region Events

        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            try
            {

                FlurryWP8SDK.Api.EndTimedEvent("DownloadList Page");
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in OnNavigatingFrom Method In Shows.cs file.", ex);
            }
            //if (adstackpl.Children.Count > 0)
            //((AdRotator.AdRotatorControl)adstackpl.Children[0]).Dispose();
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (ResourceHelper.AppName == Apps.Web_Tile.ToString() || ResourceHelper.AppName == Apps.Web_Media.ToString())
            {
                if (NavigationService.CanGoBack)
                    NavigationService.GoBack();
            }
            else
            {
                if (AppSettings.AddNewShowIconVisibility)
                {
                    NavigationService.Navigate(new Uri("/MainPage.xaml?backentryid=1", UriKind.Relative));
                }
                else
                {
                    if (AppSettings.bcount)
                    {
                        if (NavigationService.CanGoBack)
                            NavigationService.GoBack();
                    }
                    else
                    {
                        rateindex = 0;
                    }
                }
            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                FlurryWP8SDK.Api.LogPageView();
                performanceProgressBar.IsIndeterminate = true;
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in OnNavigatedTo Method In Shows.cs file.", ex);
            }
        }

        private void lbxTopRated_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {


                if (lbxTopRated.SelectedIndex != -1)
                {

                    AppSettings.ShowID = (lbxTopRated.SelectedItem as ShowList).ShowID.ToString();
                    AppSettings.ShowRating = Convert.ToDouble((lbxTopRated.SelectedItem as ShowList).Rating);
                    string title = (lbxTopRated.SelectedItem as ShowList).Title;
                    AppSettings.Title = (lbxTopRated.SelectedItem as ShowList).Title;
                    // if (WebMediaFavStatus == false)
                    //{
                    if (title == Constants.getMoreLabel)
                    {
                        performanceProgressBar.IsIndeterminate = true;
                        Constants.UIThread = true;
                        topratedCount = topratedCount + Constants.PageSize;
                        lbxTopRated.ItemsSource = OnlineShow.GetTopRatedShows(topratedCount);
                        lbxTopRated.ScrollIntoView(lbxTopRated.Items[topratedCount - Constants.PageSize]);
                        performanceProgressBar.IsIndeterminate = false;
                    }
                    else
                    {
                        if (ResourceHelper.AppName == Apps.Web_Media.ToString())
                        {
                            GetDownloadExtensions();

                        }
                        else
                        {
                            AppState.searchtitle = "";
                            PageHelper.NavigateToDetailPage(AppResources.DetailPageName, AppSettings.ShowID);
                        }
                    }
                    lbxTopRated.SelectedIndex = -1;
                    //}
                    //else
                    //{
                    //    FavoritesManager.SaveFavorites(long.Parse(AppSettings.ShowID));
                    //    FavoritesManager.SaveFavoritesForLinksForWebMedia(long.Parse(AppSettings.ShowID));
                    //    GetPageDataInBackground();
                    //}
                    //WebMediaFavStatus = false;
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in lbxTopRated_SelectionChanged event In Shows.cs file.", ex);
            }
        }

        void Instance_PlayStateChanged(object sender, EventArgs e)
        {
            try
            {
                PlayState playState = BackgroundAudioPlayer.Instance.PlayerState;
                switch (playState)
                {
                    case PlayState.Paused:
                        IEnumerable<DependencyObject> cboxes = PageHelper.GetChildsRecursive(lbxRecentlyAdded);

                        foreach (DependencyObject obj in cboxes.OfType<PerformanceProgressBar>())
                        {
                            Type type = obj.GetType();
                            if (type.Name == "PerformanceProgressBar")
                            {
                                PerformanceProgressBar cb = obj as PerformanceProgressBar;
                                if (cb.Tag.ToString() == AppSettings.ShowLinkTitle)
                                {

                                    cb.IsIndeterminate = false;
                                }
                            }
                        }

                        break;

                    case PlayState.Playing:

                        IEnumerable<DependencyObject> cboxes1 = PageHelper.GetChildsRecursive(lbxRecentlyAdded);

                        foreach (DependencyObject obj in cboxes1.OfType<PerformanceProgressBar>())
                        {
                            Type type = obj.GetType();
                            if (type.Name == "PerformanceProgressBar")
                            {
                                PerformanceProgressBar cb = obj as PerformanceProgressBar;
                                if (cb.Tag.ToString() == AppSettings.ShowLinkTitle)
                                {

                                    cb.IsIndeterminate = false;
                                }
                            }
                        }

                        break;

                }
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in Instance_PlayStateChanged Method In Shows.cs file.", ex);
            }
        }

        private void lbxRecentlyAdded_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {


                if (lbxRecentlyAdded.SelectedIndex != -1)
                {

                    AppSettings.ShowID = (lbxRecentlyAdded.SelectedItem as ShowList).ShowID.ToString();
                    AppSettings.ShowRating = Convert.ToDouble((lbxRecentlyAdded.SelectedItem as ShowList).Rating);
                    string title = (lbxRecentlyAdded.SelectedItem as ShowList).Title;
                    AppSettings.Title = (lbxRecentlyAdded.SelectedItem as ShowList).Title;
                    // if (WebMediaFavStatus == false)
                    //{
                    if (title == Constants.getMoreLabel)
                    {
                        performanceProgressBar.IsIndeterminate = true;
                        Constants.UIThread = true;
                        recentCount = recentCount + Constants.PageSize;
                        lbxRecentlyAdded.ItemsSource = OnlineShow.GetRecentlyAddedShows(recentCount);
                        lbxRecentlyAdded.ScrollIntoView(lbxRecentlyAdded.Items[recentCount - Constants.PageSize]);
                        performanceProgressBar.IsIndeterminate = false;
                    }
                    else
                    {
                        if (ResourceHelper.AppName == Apps.Web_Media.ToString())
                        {
                            GetDownloadExtensions();
                        }
                        else
                        {
                            AppState.searchtitle = "";
                            PageHelper.NavigateToDetailPage(AppResources.DetailPageName, AppSettings.ShowID);
                        }
                    }

                    lbxRecentlyAdded.SelectedIndex = -1;
                    //}
                    // else
                    // {
                    //     FavoritesManager.SaveFavorites(long.Parse(AppSettings.ShowID));
                    //     FavoritesManager.SaveFavoritesForLinksForWebMedia(long.Parse(AppSettings.ShowID));
                    //     GetPageDataInBackground();
                    // }
                    // WebMediaFavStatus = false;
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in lbxRecentlyAdded_SelectionChanged Method In Shows.cs file.", ex);
            }
        }

        private void lbxCategory_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (ResourceHelper.AppName == Apps.Web_Tile.ToString())
                {
                    if (lbxCategory.SelectedIndex != -1)
                    {
                        NavigationService.Navigate(NavigationHelper.getCategoryDetailPageForWeb(lbxCategory.SelectedItem as ShowCategories));
                        lbxCategory.SelectedIndex = -1;
                    }
                }
                else if (ResourceHelper.AppName == Apps.Cricket_Videos.ToString())
                {
                    if (lbxCategory.SelectedIndex != -1)
                    {
                        NavigationService.Navigate(NavigationHelper.getCategoryDetailPageForWeb(lbxCategory.SelectedItem as ShowCategories));
                        lbxCategory.SelectedIndex = -1;
                    }
                }

                else
                {
                    if (lbxCategory.SelectedIndex != -1)
                    {
                        NavigationService.Navigate(NavigationHelper.getCategoryDetailPage(lbxCategory.SelectedItem as CatageoryTable));
                        lbxCategory.SelectedIndex = -1;
                    }
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in lbxTopRated_SelectionChanged Method In Videos file", ex);
            }
        }

        private void imgTitle_MouseEnter(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(NavigationHelper.MainPanoramaPage);
        }

        void wcDownloadList_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            try
            {
                if (e.BytesReceived < e.TotalBytesToReceive)
                    DownloadManagerHelper.ProgressChangeStatus(e, download);

                if (e.ProgressPercentage == 100)
                {
                    var itm = download.Where(i => i.Id == int.Parse(e.UserState.ToString())).FirstOrDefault();
                    Constants.SaveDownloadList.Remove(itm);
                    GetPageDataInBackground();
                }

            }


            catch (Exception ex)
            {
                string excepmess = "Exception in wb_DownloadProgressChanged Method In Videos file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
                Exceptions.SaveExceptionInLocalStorage(excepmess);
                Exceptions.SaveOrSendExceptions("Exception in wcDownloadList_DownloadProgressChanged Method In Shows.cs file.", ex);
            }
        }

        void wcDownloadList_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            try
            {

                DownloadManagerHelper.ReadDownloadStream(e, download);

            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in wcDownloadList_OpenReadCompleted Method In Shows.cs file.", ex);
            }
        }

        private void deleterecent_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ShowDetail detailModel = new ShowDetail();
                detailModel.DeleteDownloadedShow(lbxRecentlyAdded, sender as MenuItem);
                GetPageDataInBackground();
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in deleterecent_Click Method In Shows.cs file.", ex);
            }
        }

        private void deletetoprated_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ShowDetail detailModel = new ShowDetail();
                detailModel.DeleteDownloadedShow(lbxTopRated, sender as MenuItem);
                GetPageDataInBackground();
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in deletetoprated_Click Method In Shows.cs file.", ex);
            }
        }

        private static string GetYouTubeVideoTitle(string RssDoc)
        {
            string str14 = GetTxtBtwn(RssDoc, "'VIDEO_TITLE': '", "'", 0);
            if (str14 == "") str14 = GetTxtBtwn(RssDoc, "\"title\" content=\"", "\"", 0);
            if (str14 == "") str14 = GetTxtBtwn(RssDoc, "&title=", "&", 0);
            str14 = str14.Replace(@"\", "").Replace("'", "&#39;").Replace("\"", "&quot;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("+", " ");
            AppSettings.ShowLinkTitle = str14;
            return str14;
        }
        public static string GetTxtBtwn(string input, string start, string end, int startIndex)
        {
            return GetTxtBtwn(input, start, end, startIndex, false);
        }
        private static string GetTxtBtwn(string input, string start, string end, int startIndex, bool UseLastIndexOf)
        {
            int index1 = UseLastIndexOf ? input.LastIndexOf(start, startIndex) :
                                          input.IndexOf(start, startIndex);
            if (index1 == -1) return "";
            index1 += start.Length;
            int index2 = input.IndexOf(end, index1);
            if (index2 == -1) return input.Substring(index1);
            return input.Substring(index1, index2 - index1);
        }
        public static void GetYotubeUrl(String html)
        {
            string title = string.Empty;
            var urls = new List<YouTubeUri>();
            var urlsfor480p = new List<YouTubeUri>();
            var uri = default(Uri);
            try
            {
                var match = Regex.Match(html, "url_encoded_fmt_stream_map\": \"(.*?)\"");
                var data = Uri.UnescapeDataString(match.Groups[1].Value);

                var arr = Regex.Split(data, ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"); // split by comma but outside quotes
                foreach (var d in arr)
                {
                    var url = "";
                    var signature = "";
                    var tuple = new YouTubeUri();
                    foreach (var p in d.Replace("\\u0026", "\t").Split('\t'))
                    {
                        var index = p.IndexOf('=');
                        if (index != -1 && index < p.Length)
                        {
                            try
                            {
                                var key = p.Substring(0, index);
                                var value = Uri.UnescapeDataString(p.Substring(index + 1));
                                if (key == "url")
                                    url = value;
                                else if (key == "itag")
                                    tuple.Itag = int.Parse(value);
                                else if (key == "type" && value.Contains("video/mp4"))
                                    tuple.Type = value;
                                else if (key == "sig")
                                    signature = value;
                            }
                            catch { }
                        }
                    }

                    tuple.url = url + "&signature=" + signature;
                    if (tuple.IsValid)
                        urls.Add(tuple);
                }

                var minTag = GetQualityIdentifier(YouTubeQuality.Quality720P);
                var maxTag = GetQualityIdentifier(YouTubeQuality.Quality720P);
                urlsfor480p.AddRange(urls);
                foreach (var u in urls.Where(u => u.Itag < minTag || u.Itag > maxTag).ToArray())
                    urls.Remove(u);

                var entry = urls.OrderByDescending(u => u.Itag).FirstOrDefault();
                if (entry == null)
                {
                    minTag = GetQualityIdentifier(YouTubeQuality.Quality480P);
                    maxTag = GetQualityIdentifier(YouTubeQuality.Quality480P);
                    foreach (var u in urlsfor480p.Where(u => u.Itag < minTag || u.Itag > maxTag).ToArray())
                        urlsfor480p.Remove(u);

                    entry = urlsfor480p.OrderByDescending(u => u.Itag).FirstOrDefault();
                }


                if (entry != null)
                {
                    AppSettings.YoutubeUri = entry.url;
                }

            }
            catch (Exception ex)
            {

            }
        }
        private static int GetQualityIdentifier(YouTubeQuality quality)
        {
            switch (quality)
            {
                case YouTubeQuality.Quality480P: return 18;
                case YouTubeQuality.Quality720P: return 22;
                case YouTubeQuality.Quality1080P: return 37;
            }
            throw new ArgumentException("maxQuality");
        }

        void wcYoutubeReadCompleted_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            try
            {

                //  string link = "";
                //Stream stream = (Stream)e.Result;
                //StreamReader s = new StreamReader(stream);
                //string html = s.ReadToEnd();
                //s.Close();
                //s.Dispose();
                //  stream.Close();
                //stream.Dispose();

                //GetYotubeUrl(html);
                //GetYouTubeVideoTitle(html);
                //link = AppSettings.YoutubeUri + "&title=" + AppSettings.ShowLinkTitle;
                //string name = "";
                //name = AppSettings.ShowLinkTitle.Replace(":", "").Replace("|", "").Replace(".flv", "").Replace(".", "").Replace("&", "").Replace("#", "").Replace(";", "").Replace("/", "").Replace("?", "").Replace("=", "");
                //AppSettings.ShowLinkTitle = name;
                //getyoutubeurldata(name, link, e.UserState.ToString());
                DownloadManagerHelper.YoutubeWriteStream(e, download);
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in wcYoutubeReadCompleted_OpenReadCompleted Method In Shows.cs file.", ex);
            }
        }
        //public void getyoutubeurldata(string name,string link,string folderid)
        //{
        //    try
        //    {
        //        List<DownloadStatus> downloadstatuslist = new List<DownloadStatus>();
        //        downloadstatuslist = DownloadManagerHelper.LoadList(name, link, int.Parse(folderid));
        //        download.AddRange(downloadstatuslist);
        //        Constants.SaveDownloadList.AddRange(downloadstatuslist);
        //        Constants.DownloadStatus = true;
        //        lbxdownloading.ItemsSource = null;
        //        lbxdownloading.ItemsSource = Constants.SaveDownloadList;
        //        //WebClient wc = new WebClient();
        //        //wc.DownloadProgressChanged += wc_DownloadProgressChanged;
        //        //wc.OpenReadAsync(new Uri(link, UriKind.RelativeOrAbsolute), int.Parse(folderid));
        //        //wc.OpenReadCompleted += wc_OpenReadCompleted;

        //    }
        //    catch (Exception ex)
        //    {

        //        string ec = ex.Message;
        //    }
        //}

        //void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        //{
        //    if (e.BytesReceived < e.TotalBytesToReceive)
        //        DownloadManagerHelper.ProgressChangeStatus(e, download);

        //    if (e.ProgressPercentage == 100)
        //    {
        //        var itm = download.Where(i => i.Id == int.Parse(e.UserState.ToString())).FirstOrDefault();
        //        Constants.SaveDownloadList.Remove(itm);
        //        //GetPageDataInBackground();
        //    }
        //}

        private void btnadd_Click_1(object sender, EventArgs e)
        {
            Constants.DownloadTimer.Stop();
            if (ResourceHelper.AppName == Apps.Cricket_Videos.ToString())
            {
                PageHelper.NavigateToUserUploadPage(AppResources.UserUploadPageName);
            }
            else
                PageHelper.NavigateToUserUploadPage(AppResources.UserUploadPageName);
        }

        private void ContextMenu_Opened_1(object sender, RoutedEventArgs e)
        {
            try
            {

                //MenuItem selectedItem = sender as MenuItem;
                ContextMenu menu = sender as ContextMenu;
                ListBoxItem selectedListBoxItem = lbxTopRated.ItemContainerGenerator.ContainerFromItem(menu.DataContext) as ListBoxItem;
                int showid = (selectedListBoxItem.Content as ShowList).ShowID;
                //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
                if (Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid).FirstOrDefaultAsync()).Result.Status != "Custom" && ResourceHelper.AppName != Apps.Web_Tile.ToString())
                {
                    menu.IsOpen = false;
                }
                //else
                //{
                //    menu.IsOpen = true;
                //}
                foreach (MenuItem contextMenuItem in menu.Items)
                {
                    if (contextMenuItem.Name.Contains("favorites"))
                    {
                        int showid1 = (selectedListBoxItem.Content as ShowLinks).ShowID;
                        string linktype = (selectedListBoxItem.Content as ShowLinks).LinkType;
                        if (Task.Run(async () => await Constants.connection.Table<ShowLinks>().Where(i => i.ShowID == showid1 && i.LinkType == linktype).FirstOrDefaultAsync()).Result != null)
                        {
                            if (Task.Run(async () => await Constants.connection.Table<ShowLinks>().Where(i => i.ShowID == showid1 && i.LinkType == linktype).FirstOrDefaultAsync()).Result.IsFavourite == false)
                            {
                                contextMenuItem.Header = "add to favorites";
                            }
                            else
                                contextMenuItem.Header = "remove from favorites";
                        }
                    }

                }
                if (ResourceHelper.AppName != Apps.Web_Media.ToString())
                {
                    if ((sender as ContextMenu).Items.Count == 2)
                        (sender as ContextMenu).Items.RemoveAt(1);
                }

            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in ContextMenu_Opened_1 Method In Shows.cs file.", ex);
            }
        }
        private void imgFav_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            WebMediaFavStatus = true;

        }

        private void CancelDownload_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
        {
            DownloadStatus deleteditem = download.Where(i => i.Id == DownloadCancelId).FirstOrDefault();
            DownloadManager.DeleteYoutubeDownloadUrls(DownloadCancelId);
            download.Remove(deleteditem);
            Constants.SaveDownloadList.Remove(deleteditem);

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                lbxdownloading.ItemsSource = null;
                lbxdownloading.ItemsSource = Constants.SaveDownloadList;
            });
        }

        private void lbxdownloading_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            if (lbxdownloading.SelectedIndex != -1)
            {
                var selecteditem = (lbxdownloading.SelectedItem as DownloadStatus);

                DownloadCancelId = selecteditem.Id;


            }
        }
        private void ContextMenu_Opened_2(object sender, RoutedEventArgs e)
        {
            try
            {
                ContextMenu menu = sender as ContextMenu;
                ListBoxItem selectedListBoxItem = lbxRecentlyAdded.ItemContainerGenerator.ContainerFromItem(menu.DataContext) as ListBoxItem;
                int showid = (selectedListBoxItem.Content as ShowList).ShowID;
                //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
                if (Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid).FirstOrDefaultAsync()).Result.Status != "Custom" && ResourceHelper.AppName != Apps.Web_Tile.ToString())
                {
                    menu.IsOpen = false;
                }
                //else
                //{
                //    menu.IsOpen = true;
                //}
                foreach (MenuItem contextMenuItem in menu.Items)
                {
                    if (contextMenuItem.Name.Contains("favorites"))
                    {
                        int showid1 = (selectedListBoxItem.Content as ShowLinks).ShowID;
                        string linktype = (selectedListBoxItem.Content as ShowLinks).LinkType;
                        if (Task.Run(async () => await Constants.connection.Table<ShowLinks>().Where(i => i.ShowID == showid1 && i.LinkType == linktype).FirstOrDefaultAsync()).Result != null)
                        {
                            if (Task.Run(async () => await Constants.connection.Table<ShowLinks>().Where(i => i.ShowID == showid1 && i.LinkType == linktype).FirstOrDefaultAsync()).Result.IsFavourite == false)
                            {
                                contextMenuItem.Header = "add to favorites";
                            }
                            else
                                contextMenuItem.Header = "remove from favorites";
                        }
                    }

                }
                if (ResourceHelper.AppName != Apps.Web_Media.ToString())
                {
                    if ((sender as ContextMenu).Items.Count == 2)
                        (sender as ContextMenu).Items.RemoveAt(1);
                }
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in ContextMenu_Opened_2 Method In Shows.cs file.", ex);
            }
        }

        #endregion

        private void lbxTamilAdded_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            try
            {


                if (lbxTamilAdded.SelectedIndex != -1)
                {

                    AppSettings.ShowID = (lbxTamilAdded.SelectedItem as ShowList).ShowID.ToString();
                    AppSettings.ShowRating = Convert.ToDouble((lbxTamilAdded.SelectedItem as ShowList).Rating);
                    string title = (lbxTamilAdded.SelectedItem as ShowList).Title;
                    AppSettings.Title = (lbxTamilAdded.SelectedItem as ShowList).Title;
                    if (title == Constants.getMoreLabel)
                    {
                        performanceProgressBar.IsIndeterminate = true;
                        Constants.UIThread = true;
                        tamilCount = tamilCount + Constants.PageSize;
                        lbxTamilAdded.ItemsSource = OnlineShow.GetTamilAddedShows(tamilCount);
                        lbxTamilAdded.ScrollIntoView(lbxTamilAdded.Items[tamilCount - Constants.PageSize]);
                        performanceProgressBar.IsIndeterminate = false;
                    }
                    else
                    {
                        if (ResourceHelper.AppName == Apps.Web_Media.ToString())
                        {
                            GetDownloadExtensions();

                        }
                        else
                        {
                            AppState.searchtitle = "";
                            PageHelper.NavigateToDetailPage(AppResources.DetailPageName, AppSettings.ShowID);
                        }
                    }
                    lbxTamilAdded.SelectedIndex = -1;
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in lbxTamilAdded_SelectionChanged_1 event In Shows.cs file.", ex);
            }
        }

        private void ContextMenu_Opened_3(object sender, RoutedEventArgs e)
        {
            try
            {
                ContextMenu menu = sender as ContextMenu;
                ListBoxItem selectedListBoxItem = lbxTamilAdded.ItemContainerGenerator.ContainerFromItem(menu.DataContext) as ListBoxItem;
                int showid = (selectedListBoxItem.Content as ShowList).ShowID;
                //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
                if (Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid).FirstOrDefaultAsync()).Result.Status != "Custom" && ResourceHelper.AppName != Apps.Web_Tile.ToString())
                {
                    menu.IsOpen = false;
                }
                //else
                //{
                //    menu.IsOpen = true;
                //}
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in ContextMenu_Opened_3 Method In Shows.cs file.", ex);
            }
        }

        private void deletetamil_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                ShowDetail detailModel = new ShowDetail();
                detailModel.DeleteDownloadedShow(lbxTamilAdded, sender as MenuItem);
                GetPageDataInBackground();
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in deletetamil_Click_1 Method In Shows.cs file.", ex);
            }
        }

        private void addtofav_Click_1(object sender, RoutedEventArgs e)
        {
            ListBoxItem selectedListBoxItem = lbxTopRated.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
            string showid = (selectedListBoxItem.Content as ShowList).ShowID.ToString();
            //int id=Convert.ToInt32(showid);
            // int linkid =Task.Run(async()=>await Constants.connection.Table<ShowLinks>().Where(i=>i.ShowID==id).FirstOrDefaultAsync()).Result.LinkID;
            FavoritesManager.SaveFavorites(long.Parse(showid));
            //FavoritesManager.SaveFavoritesForLinksForWebMedia(long.Parse(showid),linkid);



            //if (item.IsFavourite == true)
            //{
            //    show.FavImage = ResourceHelper.RemoveFromFavoritesImage;

            //}
            //else
            //{
            //    show.FavImage = ResourceHelper.AddToFavoritesImage;
            //}



        }

        private void addtofavrec_Click_1(object sender, RoutedEventArgs e)
        {
            ListBoxItem selectedListBoxItem = lbxRecentlyAdded.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
            string showid = (selectedListBoxItem.Content as ShowList).ShowID.ToString();
            // int id = Convert.ToInt32(showid);
            //int linkid = Task.Run(async () => await Constants.connection.Table<ShowLinks>().Where(i => i.ShowID == id).FirstOrDefaultAsync()).Result.LinkID;
            FavoritesManager.SaveFavorites(long.Parse(showid));
            //FavoritesManager.SaveFavoritesForLinksForWebMedia(long.Parse(showid), linkid);
        }

        private void renamevideo_Click_1(object sender, RoutedEventArgs e)
        {
            ListBoxItem selectedListBoxItem = lbxTopRated.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
            ShowList list = selectedListBoxItem.Content as ShowList;
            Constants.RenameLinkShowlistItem = list;
            poupRename = new Popup();
            poupRename.IsOpen = false;
            Constants.frompagename = "DownloadList";
            RenameTitle nametitle = new RenameTitle();
            poupRename.Child = nametitle;
            poupRename.IsOpen = true;
        }

        private void renamevideorecent_Click_1(object sender, RoutedEventArgs e)
        {
            ListBoxItem selectedListBoxItem = lbxRecentlyAdded.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
            ShowList list = selectedListBoxItem.Content as ShowList;
            Constants.RenameLinkShowlistItem = list;
            poupRename = new Popup();
            poupRename.IsOpen = false;
            Constants.frompagename = "DownloadList";
            RenameTitle nametitle = new RenameTitle();
            poupRename.Child = nametitle;
            poupRename.IsOpen = true;
        }

        //private void lbxUpcomingAdded_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        //{
        //    try
        //    {


        //        if (lbxUpcomingAdded.SelectedIndex != -1)
        //        {

        //            AppSettings.ShowID = (lbxUpcomingAdded.SelectedItem as ShowList).ShowID.ToString();
        //            AppSettings.ShowRating = Convert.ToDouble((lbxUpcomingAdded.SelectedItem as ShowList).Rating);
        //            string title = (lbxUpcomingAdded.SelectedItem as ShowList).Title;
        //            AppSettings.Title = (lbxUpcomingAdded.SelectedItem as ShowList).Title;
        //            if (title == Constants.getMoreLabel)
        //            {
        //                performanceProgressBar.IsIndeterminate = true;
        //                Constants.UIThread = true;
        //                upcomingCount = upcomingCount + Constants.PageSize;
        //                lbxUpcomingAdded.ItemsSource = OnlineShow.GetUpComingAddedShows(upcomingCount);
        //                lbxUpcomingAdded.ScrollIntoView(lbxUpcomingAdded.Items[upcomingCount - Constants.PageSize]);
        //                performanceProgressBar.IsIndeterminate = false;
        //            }
        //            else
        //            {
        //                if (ResourceHelper.ProjectName == Apps.DownloadManger.ToString())
        //                {
        //                    GetDownloadExtensions();
        //                }
        //                else
        //                {
        //                    AppState.searchtitle = "";
        //                    PageHelper.NavigateToDetailPage(AppResources.DetailPageName, AppSettings.ShowID);
        //                }
        //            }

        //            lbxUpcomingAdded.SelectedIndex = -1;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Exceptions.SaveOrSendExceptions("Exception in lbxUpcomingAdded_SelectionChanged_1 Method In Shows.cs file.", ex);
        //    }
        //}

        //private void deleteupcoming_Click_1(object sender, RoutedEventArgs e)
        //{
        //    try
        //    {
        //        ShowDetail detailModel = new ShowDetail();
        //        detailModel.DeleteDownloadedShow(lbxUpcomingAdded, sender as MenuItem);
        //        GetPageDataInBackground();
        //    }
        //    catch (Exception ex)
        //    {

        //        Exceptions.SaveOrSendExceptions("Exception in deleteupcoming_Click_1 Method In Shows.cs file.", ex);
        //    }
        //}

        //private void ContextMenu_Opened_4(object sender, RoutedEventArgs e)
        //{
        //    try
        //    {
        //        ContextMenu menu = sender as ContextMenu;
        //        ListBoxItem selectedListBoxItem = lbxUpcomingAdded.ItemContainerGenerator.ContainerFromItem(menu.DataContext) as ListBoxItem;
        //        int showid = (selectedListBoxItem.Content as ShowList).ShowID;
        //        //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
        //        if (Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid).FirstOrDefaultAsync()).Result.Status != "Custom" && ResourceHelper.AppName != Apps.Web_Tile.ToString())
        //        {
        //            menu.IsOpen = false;
        //        }
        //        //else
        //        //{
        //        //    menu.IsOpen = true;
        //        //}
        //    }
        //    catch (Exception ex)
        //    {

        //        Exceptions.SaveOrSendExceptions("Exception in ContextMenu_Opened_4 Method In Shows.cs file.", ex);
        //    }
        //}




    }


}